//
//  VCOfListenFMPlayInterface.m
//  LCOnePsychology
//
//  Created by li cheng on 16/9/3.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "VCOfListenFMPlayInterface.h"
#import "MJMacro.h"
#import "Masonry.h"
#import "BaseLabel.h"
#import "UIImageView+WebCache.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "ClickButtonInListenFMRootClass.h"
#import "ClickButtonInListenFMData.h"
#import "ListenFMRootClass.h"
#import "ListenFMData.h"
#import "ListenFMCategory.h"
#import "ListenFMHot_Fm.h"
#import "ListenFMNew_Fm.h"
#import "ListenFMNew_Lesson.h"
@interface VCOfListenFMPlayInterface ()
// 进度条
@property(nonatomic, strong) UISlider *progressSlider;
// 前面label,当前的时间
@property (nonatomic, strong) BaseLabel *leftTimeLabel;
// 后面label, 总共的时间
@property (nonatomic, strong) BaseLabel *rightTimeLabel;
// 上一首的按钮
@property (nonatomic, strong) UIButton *lastButton;
// 播放的案例
@property (nonatomic, strong) UIButton *playButton;
// 下一首的按钮
@property (nonatomic, strong) UIButton *nextButton;
// 声明播放视频的控件属性(可以播放视频也可以播放音频)
@property (nonatomic,strong)AVPlayer *player;
// 播放的总时长
@property (nonatomic,assign)CGFloat sumPlayOperation;
// 存放网址的 item
@property (nonatomic,strong)AVPlayerItem *playerItem;
// 该视频的总时长,用来快进快退
@property (nonatomic,assign)CGFloat totalMovieDuration;
// 上面的图片
@property (nonatomic, strong) UIImageView *aboveImageView;
// 下面的图片
@property (nonatomic, strong) UIImageView *belowImageView;
// 标题
@property (nonatomic, strong) BaseLabel *titleLabel;
// 主播的名字
@property (nonatomic, strong) BaseLabel *anchorLabel;

@end

@implementation VCOfListenFMPlayInterface

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     NSLog(@"_clickButtonInListenFMRootClass.data[0].url:%@", _mArrayOfClickButtonInListenFMData[0].url);
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (_playerItem) {
        
        [_playerItem removeObserver:self forKeyPath:@"status"];
    }
    // 创建指控件
    [self createSubViews];
    // 创建 AVPlay
    [self createAVPlayer];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_aboveImageView removeFromSuperview];
    [_belowImageView removeFromSuperview];
    
}
#pragma mark - 创建 AVPlayer
- (void)createAVPlayer{
    // 设置播放的URL
    NSURL *url = [NSURL URLWithString:_urlString];
    // 设置播放的项目
    _playerItem = [[AVPlayerItem alloc] initWithURL:url];
    // 监听status属性
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    // 初始化player对象
    self.player = [[AVPlayer alloc] initWithPlayerItem:_playerItem];
    // 设置播放进度的默认值
    self.progressSlider.value = 0;
    //    //设置播放的默认音量值
    //    self.player.volume = 0.5f;
    [self addProgressObserver];
}
#pragma mark - 监听状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status == AVPlayerStatusReadyToPlay){
            [self playSong:_playButton];
        }else if(status == AVPlayerStatusUnknown){
            NSLog(@"%@",@"AVPlayerStatusUnknown");
        }else if (status == AVPlayerStatusFailed){
            NSLog(@"%@",@"AVPlayerStatusFailed");
        }
    }
//    NSLog(@"keyPath:%@", keyPath);
//    NSLog(@"object:%@", object);
//    NSLog(@"change:%@", change);
//    NSLog(@"context:%@", context);
}
#pragma mark - 创建子控件
- (void)createSubViews{
    // 创建上面的 imageView
    self.aboveImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.bounds.size.height * 0.55)];
    [self.view addSubview:_aboveImageView];
    [self.aboveImageView sd_setImageWithURL:[NSURL URLWithString:_coverString] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
    // 创建下面的 iamgeview
    self.belowImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, _aboveImageView.bounds.size.height, SCREEN_WIDTH, self.view.bounds.size.height - _aboveImageView.bounds.size.height)];
    [self.belowImageView sd_setImageWithURL:[NSURL URLWithString:_coverString] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
    self.belowImageView.userInteractionEnabled = YES;
    [self.view addSubview:_belowImageView];
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.belowImageView.frame.size.width, _belowImageView.frame.size.height)];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [self.belowImageView addSubview:toolbar];
    // 创建 slider
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 10)];
    [self.belowImageView addSubview:_progressSlider];
    [self.progressSlider addTarget:self action:@selector(changeProgress:) forControlEvents:UIControlEventValueChanged];
    // 创建左边时间的 label
    self.leftTimeLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10, 20, 60, 10)];
    self.leftTimeLabel.font = [UIFont systemFontOfSize:10];
    self.leftTimeLabel.textColor = [UIColor whiteColor];
    self.leftTimeLabel.text = @"00:00";
    [self.belowImageView addSubview:self.leftTimeLabel];
    // 创建右边的时间的 label
    self.rightTimeLabel = [[BaseLabel alloc] init];
    self.rightTimeLabel.font = [UIFont systemFontOfSize:10];
    self.rightTimeLabel.textColor = [UIColor whiteColor];
    self.rightTimeLabel.textAlignment = 2;
    self.rightTimeLabel.text = @"00:00";
    [self.belowImageView addSubview:_rightTimeLabel];
    [self.rightTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(10);
        make.right.equalTo(self.belowImageView).offset(-10);
        make.top.equalTo(self.belowImageView).offset(20);
    }];
    // 创建标题的 Label
    self.titleLabel = [[BaseLabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = _titleString;
    self.titleLabel.textAlignment = 1;
    [self.belowImageView addSubview:_titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.belowImageView.mas_centerX);
        make.centerY.mas_equalTo(self.belowImageView).multipliedBy(0.5f);
        make.width.mas_equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    // 创建主播姓名的 Label
    self.anchorLabel = [[BaseLabel alloc] init];
    self.anchorLabel.font = [UIFont systemFontOfSize:15];
    self.anchorLabel.textColor = [UIColor whiteColor];
    NSString *stringAnchor = [NSString stringWithFormat:@"主播:%@", _speakString];
    self.anchorLabel.text = stringAnchor;
    self.anchorLabel.textAlignment = 1;
    [self.belowImageView addSubview:_anchorLabel];
    [self.anchorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(0);
        make.left.equalTo(self.view).offset(0);
        make.width.mas_equalTo(self.view);
        make.height.mas_offset(40);
    }];
    // 创建中间的 play button
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.playButton setTintColor:[UIColor whiteColor]];
    [self.belowImageView addSubview:_playButton];
    // 播放音乐
    [self.playButton addTarget:self action:@selector(playSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.playButton setImage:[UIImage imageNamed:@"PlaySong_64"] forState:UIControlStateNormal];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.belowImageView).multipliedBy(1.5);
        make.centerX.equalTo(self.belowImageView);
        if (IS_IPHONE_5) {
            make.width.height.mas_offset(60);
        } else {
            make.width.height.mas_equalTo(80);
        }
    }];
    // 创建 上一首的 button
    UIButton *lastButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [lastButton setTintColor:[UIColor whiteColor]];
    [lastButton addTarget:self action:@selector(lastSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.belowImageView addSubview:lastButton];
    [lastButton setImage:[UIImage imageNamed:@"Last_32"] forState:UIControlStateNormal];
    [lastButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.belowImageView).multipliedBy(1.5);
        make.right.equalTo(self.playButton.mas_left).offset(-10);
        if (IS_IPHONE_5) {
            make.width.height.mas_offset(40);
        } else {
            make.width.height.mas_equalTo(60);
        }
    }];
    // 创建收藏的 button
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [collectButton setTintColor:[UIColor whiteColor]];
    [self.belowImageView addSubview:collectButton];
    [collectButton setImage:[UIImage imageNamed:@"Collect-1"] forState:UIControlStateNormal];
    [collectButton addTarget:self action:@selector(pleaseWait) forControlEvents:UIControlEventTouchUpInside];
    [collectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.belowImageView).multipliedBy(1.5);
        make.right.equalTo(lastButton.mas_left).offset(-10);
        if (IS_IPHONE_5) {
            make.width.height.mas_offset(40);
        } else {
            make.width.height.mas_equalTo(60);
        }

    }];
    // 创建下一首的 button
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [nextButton setTintColor:[UIColor whiteColor]];
    [nextButton addTarget:self action:@selector(nextSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.belowImageView addSubview:nextButton];
    [nextButton setImage:[UIImage imageNamed:@"Next_32"] forState:UIControlStateNormal];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.belowImageView).multipliedBy(1.5);
        make.left.equalTo(self.playButton.mas_right).offset(10);
        if (IS_IPHONE_5) {
            make.width.height.mas_offset(40);
        } else {
            make.width.height.mas_equalTo(60);
        }

    }];
    // 创建分享的button
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [shareButton setTintColor:[UIColor whiteColor]];
    [self.belowImageView addSubview:shareButton];
    [shareButton setImage:[UIImage imageNamed:@"Share"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(pleaseWait) forControlEvents:UIControlEventTouchUpInside];
    [shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.belowImageView).multipliedBy(1.5);
        make.left.equalTo(nextButton.mas_right).offset(10);
        if (IS_IPHONE_5) {
            make.width.height.mas_offset(40);
        } else {
            make.width.height.mas_equalTo(60);
        }

    }];
    // 创建返回的 button
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame =  CGRectMake(10, 20, 60, 44);
    [backButton setTitle:@"< 返回" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize: 17.0];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
}
#pragma mark - 还未开放此功能
- (void)pleaseWait{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"这个功能目前还没有开放" message:@"你可以尝试别的东西" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 上一首 button 点击事件
- (void)lastSong:(UIButton *)button{
//    // 让下一首是当前的 +1
    if (_numberOfSelectLastSong == _mArrayOfClickButtonInListenFMData.count - 1) {
        _numberOfSelectNextSong = 0;
    } else {
        _numberOfSelectNextSong = _numberOfSelectLastSong + 1;
    }
    if (_numberOfSelectLastSong == -1) {
        _numberOfSelectLastSong = _mArrayOfClickButtonInListenFMData.count - 1;
    }
    if (_mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].url) {
        if (_numberOfSelectLastSong < _mArrayOfClickButtonInListenFMData.count) {
            
            _urlString = _mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].url;
            NSLog(@"_clickButtonInListenFMRootClass.data[0].url:%@", _clickButtonInListenFMRootClass.data[_numberOfSelectLastSong].url);
            if (_playerItem) {
                
                [_playerItem removeObserver:self forKeyPath:@"status"];
            }
            // 创建 AVPlay
            [self createAVPlayer];
            // 上面图片赋值
            [self.aboveImageView sd_setImageWithURL:[NSURL URLWithString:_mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].cover] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
            // 下面图片赋值
            [self.belowImageView sd_setImageWithURL:[NSURL URLWithString:_mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].cover] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
            // 题目赋值
            self.titleLabel.text = _mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].title;
            // 作者赋值
            self.anchorLabel.text = [NSString stringWithFormat:@"主播:%@", _mArrayOfClickButtonInListenFMData[_numberOfSelectLastSong].speak];
        }
        
    } else {
        [self pleaseWaitTwo];
    }
    _numberOfSelectLastSong--;
    NSLog(@"上一曲");
}
#pragma mark - 播放歌曲 buttton 点击事件
- (void)playSong:(UIButton *)button{
//        [_playerItem removeObserver:self forKeyPath:@"status"];
    [self.playButton setImage:[UIImage imageNamed:@"Pause"] forState:UIControlStateNormal];
    [self.playButton removeTarget:self action:@selector(playSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.playButton addTarget:self action:@selector(pasueSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.player play];
}
#pragma mark 下一首 button 点击事件
- (void)nextSong:(UIButton *)button{
    // 让上一首是当前 -1
    if (_numberOfSelectNextSong == 0 ) {
        _numberOfSelectLastSong = _mArrayOfClickButtonInListenFMData.count - 1;
    } else {
        _numberOfSelectLastSong = _numberOfSelectNextSong - 1;
    }
    if (_numberOfSelectNextSong == _mArrayOfClickButtonInListenFMData.count) {
        _numberOfSelectNextSong = 0;
    }
    if (_mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].url) {
        if (_numberOfSelectNextSong < _mArrayOfClickButtonInListenFMData.count) {
            
            _urlString = _mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].url;
            NSLog(@"_clickButtonInListenFMRootClass.data[0].url:%@", _mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].url);
            if (_playerItem) {
                
                [_playerItem removeObserver:self forKeyPath:@"status"];
            }
            // 创建 AVPlay
            [self createAVPlayer];
            // 上面图片赋值
            [self.aboveImageView sd_setImageWithURL:[NSURL URLWithString:_mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].cover] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
            // 下面图片赋值
            [self.belowImageView sd_setImageWithURL:[NSURL URLWithString:_mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].cover] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
            // 题目赋值
            self.titleLabel.text = _mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].title;
            // 作者赋值
            self.anchorLabel.text = [NSString stringWithFormat:@"主播:%@", _mArrayOfClickButtonInListenFMData[_numberOfSelectNextSong].speak];
        }
   
    } else {
        [self pleaseWaitTwo];
    }
    NSLog(@"下一曲");
    _numberOfSelectNextSong++;
}
#pragma 进度条滑动的方法
- (void)changeProgress:(UISlider *)slider{
    self.sumPlayOperation = self.player.currentItem.duration.value / self.player.currentItem.duration.timescale;
    //CMTimeMake(a,b) a表示当前时间.b表示每秒钟有多少帧
    [self.player seekToTime:CMTimeMakeWithSeconds(self.progressSlider.value * self.sumPlayOperation, self.player.currentItem.duration.timescale) completionHandler:^(BOOL finished) {
        [self.player play];
    }];
}
#pragma mark - 暂定 button 点击事件
- (void)pasueSong:(UIButton *)pasueButton{
    [pasueButton setImage:[UIImage imageNamed:@"PlaySong_64"] forState:UIControlStateNormal];
    [pasueButton removeTarget:self action:@selector(pasueSong:) forControlEvents:UIControlEventTouchUpInside];
    [pasueButton addTarget:self action:@selector(playSong:) forControlEvents:UIControlEventTouchUpInside];
    [self.player pause];
}
#pragma mark - 返回的按钮方法实现
- (void)back:(UIButton *)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 添加观察者方法
- (void)addProgressObserver{
    // block 里
    __block typeof(self) weakSelf = self;
    //设置(1,1) 设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        //当前时间
        CGFloat current = CMTimeGetSeconds(weakSelf.player.currentTime);
        //倒计时
//        CGFloat rem = duration - current;
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)duration / 60 ,(int)duration % 60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current / 60 ,(int)current % 60];
//        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT, totalT];
        // 显示进度的时间
        weakSelf.leftTimeLabel.text = currenT;
        // 显示总共的时间
        weakSelf.rightTimeLabel.text = totalT;
        //保存总时长用于手动快进和快退
        weakSelf.totalMovieDuration = duration;
        //设置进度值 当前时间/总时长
        weakSelf.progressSlider.value = current/duration;
    }];
}
#pragma mark - 利用GCD的dispatch_once的方法实现单利模式
+ (instancetype)defaultManager
{
    static VCOfListenFMPlayInterface *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
#pragma mark - 收藏中的FM不能上一曲下一曲
- (void)pleaseWaitTwo{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"收藏中的FM不能上一曲下一曲" message:@"你可以尝试别的东西" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 其他, 内存警告的问题
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
